package com.vpx.server.framework.base;

import com.vpx.server.framework.utils.ToString;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * @author xx
 * @title: vpx
 * @module 所有实体的基类，自带toString方法，子类不用再去实现
 * @description:
 * @date
 */
public class Base implements Serializable {

    private static final long serialVersionUID = 2159882864632157636L;


    @Override
    public String toString() {
        return ToString.toString(this);
    }

    /**
     * 属性拷贝
     *
     * @param clz
     * @param <T>
     * @return
     */
    public <T> T to(Class<T> clz) {
        T instance = null;
        try {
            instance = clz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(this, instance);
        return instance;
    }

    public <T extends Base> T from(Object o) {
        if (o != null) {
            BeanUtils.copyProperties(o, this, getNullPropertyNames(o));
        }
        return (T) this;
    }

    /**
     * 获取空字段
     *
     * @param source
     * @return
     */
    private String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
